<?php

namespace Common\Ext;
class SinaKline
{
    public static $sina_current_url = "https://hq.sinajs.cn/?rn=%slist=%s";   //新浪当前行情
    public static $sina_min_kline_url = "https://vip.stock.finance.sina.com.cn/forex/api/jsonp.php/var%20[symbol]_[min]_[microtime]=/NewForexService.getMinKline?symbol=[symbol]&scale=[min]&datalen=[len]";//K分线
    public static $sina_day_kline_url = "https://vip.stock.finance.sina.com.cn/forex/api/jsonp.php/var%20[symbol][day]=/NewForexService.getDayKLine?symbol=[symbol]&_=[day]";//K日线

    public function getList($symbols = "")
    {
        $milliseconds = strval(round(microtime(true) * 1000));
        $url = sprintf(self::$sina_current_url, $milliseconds, $symbols);
        $body = $this->httGet($url);
        $utf8Body = mb_convert_encoding($body, 'UTF-8', 'GB18030');
        $data = explode(';', $utf8Body);

        if (empty($data)) {
            return false;
        }
        array_pop($data);
        $list = [];
        foreach ($data as $key => $v) {
            $res = explode("=", $v);
            if (empty($res) || empty($res[1])) {
                continue;
            }
            $name = substr($res[0], 11);
            switch ($name) {
                case stripos($name, "gbp") !== false:
                    $name = "fx_sgbpusd";
                    break;
                case stripos($name, "eur") !== false:
                    $name = "fx_seurusd";
                    break;
                case stripos($name, "nzd") !== false:
                    $name = "fx_snzdusd";
                    break;
                case stripos($name, "aud") !== false:
                    $name = "fx_saudusd";
                    break;
                case stripos($name, "chf") !== false:
                    $name = "fx_schfusd";
                    break;
            }
            $res = explode(",", $res[1]);

            if (empty($res) || empty($res[1])) {
                break;
            }
            $tmp["name"] = trim($res[9]); //名称
            $tmp["price"] = $res[8]; //当前价格
            $tmp["close"] = $res[3]; //昨日收盘
            $tmp["open"] = $res[5];//开盘价
            $tmp["higher"] = $res[6];//最高
            $tmp["lower"] = $res[7];//最低
            $tmp["updownCount"] = number_format($res[8] - $res[3], 3);//涨跌
            $tmp["bofu"] = number_format($res[6] - $res[7], 3);//波幅
            $tmp["date"] = $res[10] . " " . $res[0];//当前时间
            $tmp["percent"] = (10000 * ($res[8] - $res[3]) / $res[3]) / 100 + "%"; //涨跌
            $tmp["updown"] = $res[8] > $res[3] ? "up" : "down";//涨还是跌
            $tmp["title"] = $name;
            if ($tmp["updown"] == "down") {
                $tmp["open_html"] = "<span  class='fzmmm red'>{$tmp["open"]}</span>";
                $tmp["change_html"] = "<span  class='fzmm bred' style='width: 70px;height: 30px;text-align: center;margin-top: 8px;display: -webkit-box;display: -ms-flexbox;display: flex;-webkit-box-pack: center;-ms-flex-pack: center;justify-content: center;-webkit-box-align: center;-ms-flex-align: center;align-items: center;font-size: 12px;color: #fff!important;float: right;border-radius: 3px; font-weight: 600; line-height: 25px; font-size: 14px;'>{$tmp["updownCount"]}%</span>";
            } else {
                $tmp["open_html"] = "<span  class='fzmmm green'>{$tmp["close"]}</span>";
                $tmp["change_html"] = "<span  class='fzmm bgreen' style='width: 70px;height: 30px;text-align: center;margin-top: 8px;display: -webkit-box;display: -ms-flexbox;display: flex;-webkit-box-pack: center;-ms-flex-pack: center;justify-content: center;-webkit-box-align: center;-ms-flex-align: center;align-items: center;font-size: 12px;color: #fff!important;float: right;border-radius: 3px; font-weight: 600; line-height: 25px; font-size: 14px;'>+{$tmp["updownCount"]}%</span>";
            }
            $tmp["zf"] = (10000 * ($res[6] - $res[7]) / $res[3]) / 100 + "%"; //振幅
            $list[] = $tmp;
        }
        return $list;
    }

    public function getMinLine($min, $len, $symbol)
    {
        $milliseconds = strval(round(microtime(true) * 1000));;
        $url = str_replace(["[symbol]", "[min]", "[microtime]", "[len]"], [$symbol, $min, $milliseconds, $len], self::$sina_min_kline_url);
        $body = $this->httGet($url);
        $utf8Body = mb_convert_encoding($body, 'UTF-8', 'GB18030');

        $res = explode('(', $utf8Body);
        if (empty($res) || empty($res[1])) {
            return;
        }
        $data = str_replace(");", "", $res[1]);
        $data = json_decode($data, true);
        if (empty($data)) {
            return false;
        }
        $arr = [];
        foreach ($data as $key=>$v) {
            $open = round($v["o"],4);
            $close =round($v["c"],4);
            $high =round($v["h"],4);
            $low = round($v["l"],4);
            $arr[$key] =[$v["d"],$open,$close,$high,$low];
        }
        $arr =array_reverse($arr);
        $arr = array_slice($arr,0,200);
        $list["data"] = $arr;
        $list["code"] = 0;
        return $list;
    }

    public function getDayLine($symbol)
    {
        $day = date("Y_m_d");
        $url = str_replace(["[symbol]", "[day]"], [$symbol, $day], self::$sina_day_kline_url);
        $body = $this->httGet($url);
        $content = trim($body, '"');
        $res = explode('(', $content);
        if (empty($res) || empty($res[1])) {
            return;
        }
        $str = str_replace(");", "", $res[1]);
        $str = trim($str, '"');
        $data = explode("|", $str);
        $arr = [];
        foreach ($data as $k => $v) {
            $info = explode(",", trim($v, ","));

            $arr[$k] = $info;
        }
        $arr =array_reverse($arr);
        $arr = array_slice($arr,0,100);
        $list["data"] = $arr;
        $list["code"] = 0;
        return $list;

    }

    public function http_curl($url, $type = 'get', $res = 'json', $arr = '')
    {
        $ch = curl_init();
        //2.设置curl的参数
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        if ($type == 'post') {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $arr);
        }
        //3.采集
        $output = curl_exec($ch);
        //4.关闭
        curl_close($ch);
        //如果返回的值，是json格式，则转换成数组
        if ($res == 'json') {
            if (curl_errno($ch)) {
                //请求失败，返回错误信息
                return curl_error($ch);
            } else {
                //请求成功
                return json_decode($output, true);
            }
        }
    }


    public function httGet($url)
    {
        $ua = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36';// 伪造抓取 UA
        $ip = mt_rand(11, 191) . "." . mt_rand(0, 240) . "." . mt_rand(1, 240) . "." . mt_rand(1, 240);
        // 初始化cURL会话
        $ch = curl_init();
        // 设置cURL选项
        curl_setopt($ch, CURLOPT_URL, $url); // 设置请求的URL
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 返回响应而不是直接输出
        curl_setopt($ch, CURLOPT_HEADER, false); // 不返回HTTP头
        $proxy = 'static-qiye.hailiangip.com:41663'; // 这里设置代理 IP
        curl_setopt($ch, CURLOPT_PROXY, $proxy);
        curl_setopt($ch, CURLOPT_PROXYUSERPWD, "O25031823480982418191_1:VfTs4kMO");
        curl_setopt($ch, CURLOPT_REFERER, 'https://finance.sina.com.cn/forex/');//模拟来路
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-FORWARDED-FOR:' . $ip, 'CLIENT-IP:' . $ip));  //伪造IP
        curl_setopt($ch, CURLOPT_USERAGENT, $ua);// 伪造ua
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // 允许重定向
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 关闭SSL证书验证（根据需要开启或关闭）
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 关闭SSL主机验证（根据需要开启或关闭）
        // 执行cURL会话
        $response = curl_exec($ch);
        // 检查是否有错误发生
        if (curl_errno($ch)) {
            $error_msg = curl_error($ch);
            curl_close($ch); // 关闭cURL会话
            return "cURL Error: $error_msg";
        }
        curl_close($ch);
        return $response;
    }

    public function getOne($symbols = "")
    {
        $milliseconds = strval(round(microtime(true) * 1000));
        $url = sprintf(self::$sina_current_url, $milliseconds, $symbols);
        $body = $this->httGet($url);
        $utf8Body = mb_convert_encoding($body, 'UTF-8', 'GB18030');
        $data = explode(';', $utf8Body);
        if (empty($data)) {
            return false;
        }
        array_pop($data);
        $v = $data[0];
        $res = explode("=", $v);
        if (empty($res) || empty($res[1])) {
            return false;
        }
        $name = substr($res[0], 11);
        switch ($name) {
            case stripos($name, "gbp") !== false:
                $name = "fx_sgbpusd";
                break;
            case stripos($name, "eur") !== false:
                $name = "fx_seurusd";
                break;
            case stripos($name, "nzd") !== false:
                $name = "fx_snzdusd";
                break;
            case stripos($name, "aud") !== false:
                $name = "fx_saudusd";
                break;
            case stripos($name, "chf") !== false:
                $name = "fx_schfusd";
                break;
        }
        $res = explode(",", $res[1]);

        if (empty($res) || empty($res[1])) {
            return false;
        }
        $tmp["name"] = trim($res[9]); //名称
        $tmp["price"] = $res[8]; //当前价格
        $tmp["close"] = $res[3]; //昨日收盘
        $tmp["open"] = $res[5];//开盘价
        $tmp["high"] = $res[6];//最高
        $tmp["low"] = $res[7];//最低
        $percent = (10000 * ($res[8] - $res[3]) / $res[3]) / 100 + "%"; //涨跌
        $updown = $res[8] > $res[3] ? "up" : "down";//涨还是跌
        if ($updown == "down") {
            $tmp["change"] = "<span  class='red' style='font-size:16px;'>{$percent}</span>";
            $tmp["close"] = "<span  class='red' style='font-size:22px;'>{$res[3]}</span";
        } else {
            $tmp["change"] = "<span  class='green' style='font-size:16px;'>{$percent}</span>";
            $tmp["close"] = "<span  class='green' style='font-size:22px;'>{$res[3]}</span";
        }
        return $tmp;
    }

}